/*
 * @Author: your name
 * @Date: 2021-05-17 16:13:33
 * @LastEditTime: 2021-05-17 16:26:16
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /vite-project/src/router/helper/routeHelper.ts
 */
import type {AppRouteModule, AppRouteRecordRaw} from "@/router/types"
import { createRouter, createWebHistory, Router, RouteRecordNormalized } from 'vue-router';
import { cloneDeep } from 'lodash-es';


export function flatMultiLevelRoutes(routeModules: AppRouteModule[]) {
    const modules: AppRouteModule[] = cloneDeep(routeModules);
    for (let index = 0; index < modules.length; index++) {
        const routeModule = modules[index];
        if (!isMultipleRoute(routeModule)) {
            continue;
        }
        promoteRouteLevel(routeModule);
    }
    return modules;
} 

function promoteRouteLevel(routeModule: AppRouteModule) {
    let router: Router | null = createRouter({
        routes: [(routeModule as unknown) as RouteRecordNormalized],
        history: createWebHistory(),
    });
    const routes = router.getRoutes();
    addToChildren(routes, routeModule.children || [], routeModule);
    router = null;

    routeModule.children = routeModule.children?.filter((item) => !item.children?.length);
}
// Add all sub-routes to the secondary route
function addToChildren(
  routes: RouteRecordNormalized[],
  children: AppRouteRecordRaw[],
  routeModule: AppRouteModule
) {
  for (let index = 0; index < children.length; index++) {
    const child = children[index];
    const route = routes.find((item) => item.name === child.name);
    if (!route) {
      continue;
    }
    routeModule.children = routeModule.children || [];
    if (!routeModule.children.find((item) => item.name === route.name)) {
      routeModule.children?.push((route as unknown) as AppRouteModule);
    }
    if (child.children?.length) {
      addToChildren(routes, child.children, routeModule);
    }
  }
}

function isMultipleRoute(routeModule: AppRouteModule) {

    if (!routeModule || !Reflect.has(routeModule, 'children') || !routeModule.children?.length) {
        return false;
    }

    const children = routeModule.children;

    let flag = false;
    for(let index = 0; index < children.length; index++) {
        const child = children[index];
        if (child.children?.length) {
            flag = true;
            break;
        }
    }
    return flag;
}